import urllib.request
import ssl
from lxml import etree

ssl._create_default_https_context = ssl._create_unverified_context


# 获取数据
def getPhotoData(page):
    if page == 1:
        url = 'https://sc.chinaz.com/tupian/siwameinvtupian.html'
    else:
        url = "https://sc.chinaz.com/tupian/siwameinvtupian_" + str(page) + ".html"

    headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
    }
    # 请求对象定制
    request = urllib.request.Request(url=url, headers=headers)
    response = urllib.request.urlopen(request)
    content = response.read().decode('utf-8')
    return content


# 使用xpath解析数据
def xpathData(content):
    tree = etree.HTML(content)
    src_list = tree.xpath('//body//div[@data-marginr]//div/img/@data-original')
    alt_list = tree.xpath('//body//div[@data-marginr]//div/img/@alt')

    for i in range(0, len(src_list)):
        name = alt_list[i]
        src = src_list[i]
        url = 'https:' + src
        urllib.request.urlretrieve(url=url, filename='./美女图片/' + name + '.jpg')


if __name__ == '__main__':
    page_start = int(input('请输入起始页：'))
    page_end = int(input('请输入结束页：'))
    for page in range(page_start, page_end + 1):
        content = getPhotoData(page)
        xpathData(content)
